package cn.mw.cmdb.entity;

import cn.mw.cmdb.param.ImportContextParam;
import cn.mw.components.mongodb.entity.CriteriaOpsType;
import cn.mw.components.mongodb.entity.MPropertyTypeInt;
import cn.mw.microMonitorCommon.entity.cmdb.ModelExportDataInfoParam;
import cn.mw.microMonitorCommon.entity.cmdb.MwImportResultParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.mongodb.core.query.Criteria;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

import static cn.mw.cmdb.util.ValConvertUtil.intValueConvert;

@Slf4j
public class PropertyTypeInt extends PropertyType<PropertyTypeInt, Integer> {
    public static final String ID = MPropertyTypeInt.ID;

    private MPropertyTypeInt mPropertyTypeInt = new MPropertyTypeInt();

    public PropertyTypeInt() {
        setId(ID);
        setName("整型");
        setValueTip("请输入数字");
        setSortNum(2);
    }

    public boolean validateValue(Object value, PropertyTypeRef propertyTypeRef) throws Exception {
        if (value instanceof String) {
            intValueConvert(value);
        }
        return true;
    }

    public Integer convertValue(Object value) {
        return intValueConvert(value);
    }

    @Override
    public Criteria doCriteria(CriteriaOpsType opsType, String name, Object value) {
        return mPropertyTypeInt.doCriteria(opsType, name, value);
    }

    @Override
    public CriteriaOpsType getDefaultCriteriaOpsType() {
        return CriteriaOpsType.is;
    }

    @Override
    public PropertyTypeInt newObj() {
        return new PropertyTypeInt();
    }

    @Override
    public void refresh() {

    }

    @Override
    public Object getDataValue(ImportContextParam contextParam) {
        MwImportResultParam resultParam = new MwImportResultParam();
        String message = "";
        ModelExportDataInfoParam importParam = contextParam.getParam();
        //属性名称
        String tableName = importParam.getTableName();
        Object cellValue = importParam.getCellValue();
        Map<String, Object> matchMap = new HashMap<>();
        importCheckInfo(resultParam, contextParam, matchMap);
        log.info("整数类型::");
        resultParam.setCellValue(intValueConvert(cellValue));
        resultParam.setMessage(message);
        return resultParam;
    }

    public static boolean isNumeric(Object obj) {
        String str = strValueConvert(obj);
        // 正则表达式匹配数字格式
        String numericPattern = "^[-+]?\\d*\\.?\\d+$";
        return Pattern.matches(numericPattern, str);
    }
}
